import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/util/image_utils.dart';
import 'package:flutter_taotaoshipin/util/other_utils.dart';
import 'package:path/path.dart' as path;

/// 图片加载（支持本地与网络图片）
class LoadImage extends StatelessWidget {
  const LoadImage(
    this.image, {
    super.key,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.format = ImageFormat.png,
    this.holderImg = 'none',
    this.cacheWidth,
    this.cacheHeight,
    this.alignment = Alignment.center,
  });

  final String image;
  final double? width;
  final double? height;
  final BoxFit fit;
  final ImageFormat format;
  final String? holderImg;
  final int? cacheWidth;
  final int? cacheHeight;
  final Alignment alignment;

  @override
  Widget build(BuildContext context) {
    if (image.isEmpty || image.startsWith('http')) {
      final Widget? holder = holderImg == null
          ? null
          : LoadAssetImage(
              holderImg!,
              width: width,
              height: height,
              fit: BoxFit.fill,
            );
      return CachedNetworkImage(
        imageUrl: image,
        width: width,
        height: height,
        memCacheWidth: cacheWidth,
        memCacheHeight: cacheHeight,
        fit: fit,
        placeholder: holder == null ? null : (context, url) => holder,
        errorWidget: holder == null ? null : (context, url, error) => holder,
        alignment: alignment,
      );
    }
    return LoadAssetImage(
      image,
      width: width,
      height: height,
      cacheWidth: cacheWidth,
      cacheHeight: cacheHeight,
      fit: fit,
      format: format,
      alignment: alignment,
    );
  }
}

/// 加载本地资源图片
class LoadAssetImage extends StatelessWidget {
  const LoadAssetImage(
    this.image, {
    super.key,
    this.width,
    this.height,
    this.cacheWidth,
    this.cacheHeight,
    this.fit,
    this.format = ImageFormat.png,
    this.color,
    this.alignment = Alignment.center,
  });

  final String image;
  final double? width;
  final double? height;
  final int? cacheWidth;
  final int? cacheHeight;
  final BoxFit? fit;
  final ImageFormat format;
  final Color? color;
  final Alignment alignment;

  @override
  Widget build(BuildContext context) {
    return Image.asset(
      ImageUtils.getImagePath(image, format: format),
      width: width,
      height: height,
      cacheWidth: cacheWidth,
      cacheHeight: cacheHeight,
      fit: fit,
      color: color,
      excludeFromSemantics: true, // 忽略图片语义
      gaplessPlayback: true,
      alignment: alignment,
    );
  }
}
